﻿using Growatt.DuiHelpers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Vosc.Logging;

namespace Vosc
{
    // Token: 0x02000010 RID: 16
    internal class DspDataSaveFileDataLoader
    {
        // Token: 0x06000069 RID: 105 RVA: 0x00008110 File Offset: 0x00006310
        public DspDataSaveFileDataLoader(string filepath)
        {
            if (string.IsNullOrEmpty(filepath))
            {
                throw new ArgumentNullException("filepath");
            }
            this.filepath = filepath;
        }

        // Token: 0x0600006A RID: 106 RVA: 0x00008134 File Offset: 0x00006334
        public DspDataSaveFileStruct GetFileStruct()
        {
            if (!File.Exists(this.filepath))
            {
                InternalLoggerFactory.Logger.Error(string.Format("file:{0} is not exist", this.filepath));
                return null;
            }
            DspDataSaveFileStruct result;
            try
            {
                DspDataSaveFileStruct dspDataSaveFileStruct = new DspDataSaveFileStruct();
                using (StreamReader streamReader = new StreamReader(this.filepath, Encoding.ASCII))
                {
                    string text = streamReader.ReadLine();
                    string[] array = text.Split(new char[]
                    {
                        ','
                    });
                    dspDataSaveFileStruct.SampleFrequency = int.Parse(array[0]);
                    for (int i = 1; i < array.Length; i++)
                    {
                        string[] array2 = array[i].Split(new char[]
                        {
                            '#'
                        });
                        SignalInfo signalInfo = new SignalInfo();
                        signalInfo.Address = int.Parse(array2[0], NumberStyles.HexNumber);
                        if (array2.Length==3)
                            signalInfo.Name = array2[2];
                        else
                            signalInfo.Name = string.Empty;
                        signalInfo.Type = (ENUM_001)Enum.Parse(typeof(ENUM_001), array2[1], true);

                        dspDataSaveFileStruct.Signals.Add(signalInfo);
                    }
                    result = dspDataSaveFileStruct;
                }
            }
            catch (Exception exception)
            {
                InternalLoggerFactory.Logger.Error(string.Format("file:{0} load error", this.filepath), exception);
                result = null;
            }
            return result;
        }

        // Token: 0x0600006B RID: 107 RVA: 0x00008274 File Offset: 0x00006474
        public List<ChannelBufferFile> Load(int[] dataSNs)
        {
            if (dataSNs == null || dataSNs.Length == 0)
            {
                throw new ArgumentNullException("dataSNs");
            }
            DspDataSaveFileStruct fileStruct = this.GetFileStruct();
            if (fileStruct == null)
            {
                InternalLoggerFactory.Logger.Error(string.Format("file:{0} struct load error", this.filepath));
                return null;
            }
            List<ChannelBufferFile> result;
            foreach (int num in dataSNs)
            {
                if (num >= fileStruct.Signals.Count || num < 0)
                {
                    InternalLoggerFactory.Logger.Error(string.Format("data sn {0} error", num));
                    result = null;
                    return result;
                }
            }
            List<ChannelBufferFile> list = new List<ChannelBufferFile>();
            try
            {
                if (!Directory.Exists(SystemSetting.INTERNAL_DATA_DIR))
                {
                    Directory.CreateDirectory(SystemSetting.INTERNAL_DATA_DIR);
                }
                for (int j = 0; j < dataSNs.Length; j++)
                {
                    ChannelBufferFile channelBufferFile = new ChannelBufferFile();
                    channelBufferFile.ChSN = dataSNs[j] + 1;
                    channelBufferFile.Filepath = string.Format("{0}\\{1}_{2}", SystemSetting.INTERNAL_DATA_DIR, channelBufferFile.ChSN.ToString(), DateTime.Now.ToString("yyyyMMddHHmmss"));
                    list.Add(channelBufferFile);
                    try
                    {
                        channelBufferFile.Filestream = File.Create(channelBufferFile.Filepath);
                        channelBufferFile.Filestream.WriteByte((byte)(fileStruct.SampleFrequency >> 8 & 255));
                        channelBufferFile.Filestream.WriteByte((byte)(fileStruct.SampleFrequency & 255));
                        channelBufferFile.Filestream.WriteByte(0);
                        channelBufferFile.Filestream.WriteByte(0);
                        var data = (byte)fileStruct.Signals[dataSNs[j]].Type;
                        ENUM_001 t = fileStruct.Signals[dataSNs[j]].Type;
                        if (t == ENUM_001.U16)
                            data = 0;
                        if (t == ENUM_001.I16 || t == ENUM_001.F32)
                            data = 1;
                        var data2 = (byte)(data >> 8 & 255);
                        channelBufferFile.Filestream.WriteByte(data2);
                        channelBufferFile.Filestream.WriteByte((byte)(data & 255));
                    }
                    catch (Exception innerException)
                    {
                        throw new Exception(string.Format("open file: {0} failed", channelBufferFile.Filepath), innerException);
                    }
                }
                using (StreamReader streamReader = new StreamReader(this.filepath, Encoding.ASCII))
                {
                    streamReader.ReadLine();
                    for (; ; )
                    {
                        string text = streamReader.ReadLine();
                        if (string.IsNullOrEmpty(text))
                        {
                            goto IL_35A;
                        }
                        string[] array = text.Split(new char[]
                        {
                            ','
                        });
                        if (array.Length != fileStruct.Signals.Count + 1)
                        {
                            break;
                        }
                        if (string.IsNullOrEmpty(array[0]))
                        {
                            using (List<ChannelBufferFile>.Enumerator enumerator = list.GetEnumerator())
                            {
                                while (enumerator.MoveNext())
                                {
                                    ChannelBufferFile channelBufferFile2 = enumerator.Current;
                                    channelBufferFile2.Filestream.WriteByte(0);
                                    channelBufferFile2.Filestream.WriteByte(0);
                                    channelBufferFile2.Filestream.WriteByte(0);
                                }
                                continue;
                            }
                        }
                        try
                        {
                            using (List<ChannelBufferFile>.Enumerator enumerator2 = list.GetEnumerator())
                            {
                                while (enumerator2.MoveNext())
                                {
                                    ChannelBufferFile channelBufferFile3 = enumerator2.Current;
                                    ushort num2;
                                    if (fileStruct.Signals[channelBufferFile3.ChSN - 1].Type == ENUM_001.I16)
                                    {
                                        //num2 = (ushort)short.Parse(array[channelBufferFile3.ChSN]);
                                        //channelBufferFile3.Filestream.WriteByte((byte)(num2 >> 8 & 255));
                                        //channelBufferFile3.Filestream.WriteByte((byte)(num2 & 255));
                                        //channelBufferFile3.Filestream.WriteByte(1);
                                        short num1;
                                        double number = double.Parse(array[channelBufferFile3.ChSN]);
                                        short result_number;

                                        int decimalPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2]; // 获取小数位数

                                        if (decimalPlaces == 0)
                                        {
                                            result_number = (short)(number); // 如果是一位小数，乘以10
                                            num1 = result_number;
                                        }
                                        else
                                        {
                                            int multiplier = (int)Math.Pow(10, decimalPlaces); // 计算乘数
                                            result_number = (short)(number * multiplier); // 乘以对应的乘数
                                            num1 = result_number;

                                            fileStruct.Signals[channelBufferFile3.ChSN - 1].DecimalCount = multiplier;
                                            channelBufferFile3.DecimalCount = multiplier;
                                        }

                                        channelBufferFile3.Filestream.WriteByte((byte)(num1 >> 8 & 255));
                                        channelBufferFile3.Filestream.WriteByte((byte)(num1 & 255));
                                        channelBufferFile3.Filestream.WriteByte(1);

                                    }
                                    else if (fileStruct.Signals[channelBufferFile3.ChSN - 1].Type == ENUM_001.U16)
                                    {
                                        //num2 = ushort.Parse(array[channelBufferFile3.ChSN]);
                                        //channelBufferFile3.Filestream.WriteByte((byte)(num2 >> 8 & 255));
                                        //channelBufferFile3.Filestream.WriteByte((byte)(num2 & 255));
                                        //channelBufferFile3.Filestream.WriteByte(1);

                                        double number = double.Parse(array[channelBufferFile3.ChSN]);
                                        ushort result_number;

                                        int decimalPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2]; // 获取小数位数

                                        if (decimalPlaces == 0)
                                        {
                                            result_number = (ushort)(number); // 如果是一位小数，乘以10
                                            num2 = result_number;
                                        }
                                        else
                                        {
                                            int multiplier = (int)Math.Pow(10, decimalPlaces); // 计算乘数
                                            result_number = (ushort)(number * multiplier); // 乘以对应的乘数
                                            num2 = result_number;

                                            fileStruct.Signals[channelBufferFile3.ChSN - 1].DecimalCount = multiplier;
                                            channelBufferFile3.DecimalCount = multiplier;
                                        }

                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 >> 8 & 255));
                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 & 255));
                                        channelBufferFile3.Filestream.WriteByte(1);
                                    }
                                    else if (fileStruct.Signals[channelBufferFile3.ChSN - 1].Type == ENUM_001.F32)
                                    {

                                        double number = double.Parse(array[channelBufferFile3.ChSN]);
                                        ushort result_number;

                                        int decimalPlaces = BitConverter.GetBytes(decimal.GetBits((decimal)number)[3])[2]; // 获取小数位数

                                        if (decimalPlaces == 0)
                                        {
                                            result_number = (ushort)(number); // 如果是一位小数，乘以10
                                            num2 = result_number;
                                        }
                                        else
                                        {
                                            int multiplier = (int)Math.Pow(10, decimalPlaces); // 计算乘数
                                            result_number = (ushort)(number * multiplier); // 乘以对应的乘数
                                            num2 = result_number;

                                            fileStruct.Signals[channelBufferFile3.ChSN - 1].DecimalCount = multiplier;
                                            channelBufferFile3.DecimalCount = multiplier;
                                        }

                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 >> 8 & 255));
                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 & 255));
                                        channelBufferFile3.Filestream.WriteByte(1);
                                    }
                                    else if (fileStruct.Signals[channelBufferFile3.ChSN - 1].Type == ENUM_001.MultiBit || fileStruct.Signals[channelBufferFile3.ChSN - 1].Type == ENUM_001.SingleBit)
                                    {
                                        num2 = ushort.Parse(array[channelBufferFile3.ChSN]);
                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 >> 8 & 255));
                                        channelBufferFile3.Filestream.WriteByte((byte)(num2 & 255));
                                        channelBufferFile3.Filestream.WriteByte(1);
                                    }

                                }
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {

                            DuiHelperLog.WriteErrorLog(ex);
                        }
                    }
                    throw new Exception(string.Format("file {0} format error", this.filepath));
                IL_35A:;
                }
                result = list;
            }
            catch (Exception exception)
            {
                InternalLoggerFactory.Logger.Error(string.Format("load file {0} error", this.filepath), exception);
                result = null;
            }
            finally
            {
                if (list != null && list.Count != 0)
                {
                    foreach (ChannelBufferFile channelBufferFile4 in list)
                    {
                        if (channelBufferFile4.Filestream != null)
                        {
                            channelBufferFile4.Filestream.Close();
                            channelBufferFile4.Filestream = null;
                        }
                    }
                }
            }
            return result;
        }

        // Token: 0x040000A0 RID: 160
        private string filepath;
    }
}
